<template>
  <div class="client-manager">
    <div class="search-box">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button type="primary" :disabled="!selectData.length" @click="handelCancelChurn">取消流失</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" style="display: flex">
          <el-input
            v-model="searchKeyword"
            class="search-input"
            clearable
            placeholder="请输入姓名、地址、电话"
            :suffix-icon="Search"
            @keyup.enter="handelSearch"
          />
          <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" :icon="Upload" @click="exportData">导出</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table
      ref="clientLoseRef"
      v-loading="isLoading"
      element-loading-text="数据加载中..."
      :data="tableData"
      stripe
      style="width: 100%"
      border
      :header-cell-style="{ background: '#F2F6FC', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
      :row-class-name="tableRowClassName"
      :header-cell-class-name="tableCellClass"
      row-key="customerId"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" reserve-selection width="55" fixed="left" />
      <el-table-column prop="name" label="客户姓名" fixed="left" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="client-name" @click="handelClientName(row)">{{ row.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          <el-popover placement="right" width="210" trigger="click" :show-arrow="false">
            <template #reference>
              <div class="client-phone" @click="handelShowInfo(row)">
                <span>{{ row.mobileAllShow ? row.mobileCode : hidePhone(`${row.mobileCode}`) }}</span>
                <el-icon><PhoneFilled /></el-icon>
              </div>
            </template>
            <div class="client-info">
              <div class="client-info-item">
                <UserFilled />
                <span class="client-info-item__label">姓名</span>
                <span class="client-info-item__value">{{ popoverInfo.customerName }}</span>
              </div>
              <div class="client-info-item">
                <PhoneFilled />
                <span class="client-info-item__label">电话</span>
                <span class="client-info-item__value">{{ popoverInfo.mobileCode }}</span>
              </div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="residence" label="地址" width="300" show-overflow-tooltip></el-table-column>
      <el-table-column prop="applyDate" label="流失申请日期" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="lostName" label="申请人" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column label="流失详情" width="100">
        <template #default="{ row }">
          <el-button type="primary" size="small" link @click="handelLoseDetail(row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="portaintName" label="客户画像" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="area" label="房屋面积" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="totalPriceLevelName" label="房屋总价等级" width="110" show-overflow-tooltip></el-table-column>
      <el-table-column prop="fromTypeName" label="客户来源" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="fromDetailTypeName" label="细分渠道" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="houseTypeName" label="房屋类型" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="fitmentName" label="装修用途" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="businessTypeName" label="业务类型" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="budgetName" label="客户预算" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column label="是否期房" width="100" show-overflow-tooltip>
        <template #default="{ row }"> {{ row.isFutures === 1 ? "是" : "否" }} </template>
      </el-table-column>
      <el-table-column prop="customerCureTask" label="客户阶段" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="newTrackDate" label="最后跟进日期" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="newTrackDesc" label="跟进记录" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="noTrackDays" label="未跟进天数" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="nextDateTine" label="下次跟进日期" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column
        width="200"
        show-overflow-tooltip
        v-for="item in customLabels"
        :key="item.field"
        :prop="item.field"
        :label="item.fieldName"
      />
      <el-table-column prop="remark" label="备注" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createBy" label="创建人" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="200" show-overflow-tooltip></el-table-column>
    </el-table>
    <custom-pagination
      :total="listTotal"
      v-model:limit="pageParams.size"
      v-model:page="pageParams.current"
      layout="total, slot, prev, pager, next, jumper"
      @pagination="handelPage"
    >
      <template #default>
        <el-select style="margin-left: 16px" v-model="pageParams.size" @change="handelPageSize">
          <el-option v-for="(item, index) in pageSizes" :key="`${item.label}${index}`" :label="item.label" :value="item.value" />
        </el-select>
      </template>
    </custom-pagination>

    <!--  流失详情 start  -->
    <div class="client-lose-drawer">
      <el-drawer v-model="isLoseDetail" destroy-on-close @closed="handelLoseDrawer">
        <template #header> <title-view title="流失申请" /></template>
        <template #default>
          <div class="lose-application-info" v-loading="isLoseFormLoading">
            <div class="info-item" v-for="item in loseFormItems" :key="item.id">
              <span>{{ item.title }}：</span>
              <span>{{ loseFormData[item.id] }}</span>
            </div>
          </div>
          <div class="application-record">
            <div class="record-title">
              <span>审批记录</span>
            </div>
            <div class="steps-container" v-loading="isLoseFormLoading">
              <el-steps direction="vertical" :active="stepsActive">
                <el-step v-for="item in progressArr" :key="item.nodeId">
                  <template #icon>
                    <AvatarView
                      :info="item.user"
                      avatarName="name"
                      :avatarStyle="{
                        width: '50px',
                        height: '50px',
                        radius: '50%',
                        'flex-shrink': 0
                      }"
                    />
                  </template>
                  <template #title>
                    <div>
                      <div class="step-name">{{ item.user.name }}</div>
                      <div class="step-opt">{{ item.name }}({{ approvalResult(item.result).value }})</div>
                    </div>
                    <span class="step-date">{{ item.startTime }}</span>
                  </template>
                  <template #description>
                    <div v-if="item.comment?.length">
                      <el-input type="textarea" disabled :value="comment(item)"></el-input>
                    </div>
                  </template>
                </el-step>
              </el-steps>
            </div>
          </div>
        </template>
      </el-drawer>
    </div>
    <!--  流失详情 end  -->
  </div>
</template>

<script>
export default {
  name: "clientLose"
};
</script>

<script setup>
import { ref, getCurrentInstance, computed } from "vue";
import { dayjs } from "element-plus";
import { Search, PhoneFilled, UserFilled, Upload } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import usePageList from "@/hooks/usePageList";
import useComputedParams from "@/hooks/useComputedParams";
import { hidePhone } from "@/utils";
import { tableRowClassName, tableCellClass } from "@/views/loseClient/clientLose/utils";
import { listLose, cancelLoss, approvalDataByInstanceId, exportLoseData } from "@/apis/clientLose";
import { pageSizes as sizeArr } from "@/views/loseClient/clientLose/config";
import { documentFlow } from "@/utils/downFile";
import AvatarView from "@/components/customComponents/AvatarView/index.vue";

const { proxy } = getCurrentInstance();
const router = useRouter();

/**
 * 流失列表
 */
const searchKeyword = ref("");
const customLabels = computed(() => {
  const data = listData.value;
  return data?.length ? data[0].customList ?? [] : [];
});
const tableData = computed(() => {
  const data = listData.value || [];
  return data.map(item => {
    return {
      ...item,
      ...item.dynamicFields
    };
  });
});
const pageSizes = computed(() => {
  const sizes = [...sizeArr];
  // sizes[sizes.length - 1].value = listTotal.value;
  return sizes;
});
const { isLoading, listData, listTotal, pageParams, getListData, handelPage, handelPageSize, handelSearch } = usePageList(
  listLose,
  {
    name: searchKeyword
  }
);

/**
 * 取消流失
 */
const selectData = ref([]);
const selectionChange = data => {
  selectData.value = data;
  if (selectData.value.length > 1) {
    let del_row = selectData.value.shift();
    proxy.$refs.clientLoseRef.toggleRowSelection(del_row, false);
  }
};
const handelCancelChurn = () => {
  cancelLoss(selectData.value[0].customerId).then(() => {
    selectData.value.length = 0;
    getListData();
    proxy.$modal.msgSuccess("取消流失成功");
  });
};

/**
 * 联系
 */
const popoverInfo = ref({
  name: "",
  phone: ""
});
const handelShowInfo = data => {
  popoverInfo.value = data || { name: "", phone: "" };
};

/**
 * 客户详情
 */
const handelClientName = data => {
  router.push({
    path: "/client-lose-info",
    query: {
      customerId: data.customerId
    }
  });
};
/**
 * 流失详情
 */
const isLoseDetail = ref(false);
const isLoseFormLoading = ref(false);
const stepsActive = ref(0);
const loseFormData = ref([]);
const loseFormItems = ref([]);
const progressArr = ref([]);
const approvalStatusMaps = new Map([
  ["complete", "发起申请"],
  ["agree", "已同意"],
  ["refuse", "已拒绝"]
]);
const approvalResult = useComputedParams(data => {
  if (!data) {
    return "审批中...";
  }
  if (approvalStatusMaps.get(data)) {
    return approvalStatusMaps.get(data) || "";
  }
  return "";
});
const comment = computed(() => {
  return data => {
    return data?.comment?.length ? data?.comment[0]?.text : "";
  };
});
const handelLoseDetail = async row => {
  try {
    isLoseFormLoading.value = true;
    isLoseDetail.value = true;
    const { data } = await approvalDataByInstanceId(row.processId, row.instanceId);
    isLoseFormLoading.value = false;
    loseFormItems.value = data?.processProgressVo?.formItems || [];
    loseFormData.value = data?.processProgressVo?.formData || [];
    progressArr.value = data?.processProgressVo?.progress || [];
    stepsActive.value = data?.processProgressVo?.version || 0;
  } catch (err) {
    isLoseFormLoading.value = false;
  }
};
const handelLoseDrawer = () => {
  loseFormItems.value = [];
  loseFormData.value = [];
  progressArr.value = [];
};

//导出
const exportData = () => {
  proxy.$modal
    .confirm("您确定要导出吗?")
    .then(async () => {
      isLoading.value = true;
      const res = await exportLoseData(searchKeyword.value);
      const fileName = "流失客户-" + dayjs().format("YYYYMMDDHHmmss");
      documentFlow(res, fileName, "xlsx");
      isLoading.value = false;
    })
    .catch(() => {});
};
</script>

<style scoped lang="scss">
@use "clientLose";
</style>
